package net.sppan.blog.utils;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class AESUtil {

	private static String AES_KEY = "CWELWRREW4567i1o";
	private static final Logger logger = LoggerFactory.getLogger(AESUtil.class);

	public static void main(String[] args) {
		System.out.println(encrypt("85de5b10-b30a-4553-877e-813d738d8e8c"));
		System.out.println(desEncrypt("LvLG1INT7uXDFAavaGUZJ7KBaN2h8Rr3zCqaa83gKPChpQ3mTUMs5AZZjR/mfVFcZOlKCXfI61Or5Okg6K15/iH+RDkVDLuBIPBh6fPkJOVQ0N2sV9KdXYxhvoPuye1x/loeTlCeCpIbVMJdhzalNg=="));
		System.out.println(desEncrypt("8B8s9waEm2+69lk7JmxpcaI68poYt8qKcPYlL+ymQ+atZ9559CZngD/IFd/n1XAcxoi7bn7Y6klvf2XodT3eTwabVc88x/AtFZpB/dkkpttFm7cqDjqT3ArLG9gHlMwDZJsnlAyaFdguFX+1oirfAMI5og7BZToZf9kby5RtQ9HcPHW1G/2ucNDCXB+StZ7sfW8SPDyYc+RvDftFZPb9Wg=="));
		String str = "{\"hardwareID\":\"8E6C7DB2E52338C669AAD8696E8CAC4E\",\"userName\":\"subuser1\",\"timespam\":1526139312943,\"appVersion\":\"1.0\",\"userPwd\":\"d93a5def7511da3d0f2d171d9c344e91\"}";
		System.out.println(encrypt(str));
	}

	public static String encrypt(String data) {
		try {
			Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
			int blockSize = cipher.getBlockSize();

			byte[] dataBytes = data.getBytes();
			int plaintextLength = dataBytes.length;
			if (plaintextLength % blockSize != 0) {
				plaintextLength = plaintextLength + (blockSize - (plaintextLength % blockSize));
			}

			byte[] plaintext = new byte[plaintextLength];
			System.arraycopy(dataBytes, 0, plaintext, 0, dataBytes.length);
			if (AES_KEY.equals("")) {
				AES_KEY = "CWELWRREW4567i1o";
			}

			SecretKeySpec keyspec = new SecretKeySpec(AES_KEY.getBytes("UTF-8"), "AES");
			IvParameterSpec ivspec = new IvParameterSpec(AES_KEY.getBytes());

			cipher.init(Cipher.ENCRYPT_MODE, keyspec, ivspec);
			byte[] encrypted = cipher.doFinal(plaintext);

			return Base64.encodeBase64String(encrypted).trim();

		} catch (Exception e) {
			logger.error("encrypt error : " + e);
		} catch (OutOfMemoryError e) {
			logger.error("encrypt error : " + e);
		}
		return null;
	}

	public static String desEncrypt(String data) {
		try {
			byte[] encrypted1 = Base64.decodeBase64(data);
			Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
			SecretKeySpec keyspec = new SecretKeySpec(AES_KEY.getBytes("UTF-8"), "AES");
			IvParameterSpec ivspec = new IvParameterSpec(AES_KEY.getBytes());

			cipher.init(Cipher.DECRYPT_MODE, keyspec, ivspec);

			byte[] original = cipher.doFinal(encrypted1);
			return new String(original, "UTF-8");
		} catch (Exception e) {
			//			SDKLogger.e(null, "desEncrypt error : " + e);
		} catch (OutOfMemoryError e) {
			logger.error("encrypt error : " + e);
		}
		return null;
	}

}